package com.learn.service.second.api.impl;

import com.alibaba.fastjson.JSONObject;
import com.learn.service.second.api.base.BaseApiService;
import com.learn.service.second.api.base.BaseResponse;
import com.learn.service.second.api.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送短信接口
 */
@RestController
@CrossOrigin
@RequestMapping("/mobile")
public class AliyunServiceImpl extends BaseApiService<JSONObject> {

    //随机生成六位数字验证
    public String getPwd(){
        int newNum = (int)((Math.random()*9+1)*100000);
        return String.valueOf(newNum);
    }
    Map<String, String> querys = new HashMap<String, String>();

    @RequestMapping("/t.do" )
    public void t(HttpServletRequest request, PrintWriter out) {
        String host = "http://yzx.market.alicloudapi.com";
        String path = "/yzx/sendSms";
        String method = "POST";
        String appcode = "eb9ed34b231c4415993bee542835af97";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        querys.put("mobile", request.getParameter("phone"));
        querys.put("param", "code:"+getPwd());
        //querys.put("param", "这里填写你和商家定义的变量名称和变量值填写格式看上一行代码");
        querys.put("tpl_id", "TP2007125");
        Map<String, String> bodys = new HashMap<String, String>();
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());

            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/loginPhone")
    public BaseResponse<JSONObject> loginPhone(HttpServletRequest request)throws Exception {
            int yz = Integer.parseInt(request.getParameter("resetpwd_sms"));//验证码
            System.out.println("************"+querys.get("param").substring(5)+"************");
            if (Integer.parseInt(querys.get("param").substring(5)) != yz) {
                return setResultError("验证码错误");
            }
            return setResultSuccess("验证码正确");
    }
}
